package com.ct.boss.demo.controller;

import com.ct.boss.demo.annotation.UserLogin;
import com.ct.boss.demo.http.HttpResult;
import com.ct.boss.demo.model.SysUser;
import com.ct.boss.demo.page.PageRequest;
import com.ct.boss.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author ChenTong
 * @version 1.0
 * @description 用户管理逻辑控制
 * @date 2020/6/16 20:30
 * @modified
 **/
@Validated
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * @description 利用分页工具获取用户数据列表
     * @author ChenTong
     * @param pageQuery 分页查询条件 size num
     * @return com.ct.boss.demo.http.HttpResult 响应封装
     * @date 2020/6/16 21:58
     */
    @GetMapping(value = "/users")
    public HttpResult findPage(@Valid PageRequest pageQuery){
        return HttpResult.ok(userService.findPage(pageQuery));
    }

    /**
     * @description 添加新的用户 需要用户提前登录
     * @author ChenTong
     * @param record
     * @return com.ct.boss.demo.http.HttpResult
     * @date 2020/6/16 9:36
     */
    @UserLogin
    @PostMapping(value="/save")
    public HttpResult save(@RequestBody @Valid UserVO record) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(record.getUsername());
        sysUser.setPassword(record.getPassword());
        sysUser.setEmail(record.getEmail());
        sysUser.setMobile(record.getEmail());
        return HttpResult.ok(userService.save(sysUser));
    }

    /**
     * @description 根据id删除数据
     * @author ChenTong
     * @param id
     * @return com.ct.boss.demo.http.HttpResult
     * @date 2020/6/16 10:48
     */
    @UserLogin
    @DeleteMapping("/delete/{id}")
    public HttpResult delete(@PathVariable("id") Long id){
        return HttpResult.ok(userService.delete(id));
    }

    /**
     * @description 更新用户数据
     * @author ChenTong
     * @param record
     * @return com.ct.boss.demo.http.HttpResult
     * @date 2020/6/17 11:31
     */
    @UserLogin
    @PutMapping("/update/{id}")
    public HttpResult update(@PathVariable("id") Long id,@RequestBody UserVO record){
        SysUser sysUser = new SysUser();
        sysUser.setMobile(record.getMobile());
        sysUser.setUserId(id);
        sysUser.setEmail(record.getEmail());
        return HttpResult.ok(userService.update(sysUser));
    }
}
